package com.atao.baokede.service.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import com.atao.baokede.mapper.CategoryMapper;
import com.atao.baokede.pojo.Category;
import com.atao.baokede.pojo.PageBean;
import com.atao.baokede.pojo.PageBeanWithTotalPage;
import com.atao.baokede.service.CategoryService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.atao.baokede.constant.CategoryConstant.CATEGORY_SIZE;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CategoryMapper categoryMapper;


    @Override
    public PageBeanWithTotalPage<Category> list(Integer pageNum) {
        String key = "categoryList";
        PageBean<Category> pb = new PageBean<>();
        
        // 从Redis获取数据
        List<Category> allCategories = null;
        try {
            allCategories = (List<Category>) redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            // 如果反序列化出错，删除缓存
            redisTemplate.delete(key);
        }
        
        // 如果缓存不存在或者出错，从数据库获取
        if (allCategories == null) {
            System.out.println("从数据库获取数据");
            allCategories = categoryMapper.list();
            // 设置缓存，使用秒为单位
            redisTemplate.opsForValue().set(key, allCategories);
            // 单独设置过期时间，确保正确设置
            redisTemplate.expire(key, 3600, java.util.concurrent.TimeUnit.SECONDS);
        } else {
            System.out.println("从缓存获取数据");
        }
        
        // 手动分页
        int totalSize = allCategories.size();
        int startIndex = (pageNum - 1) * CATEGORY_SIZE;
        int endIndex = Math.min(startIndex + CATEGORY_SIZE, totalSize);
        
        // 防止索引越界
        List<Category> pageItems;
        if (startIndex >= totalSize) {
            pageItems = List.of();
        } else {
            pageItems = allCategories.subList(startIndex, endIndex);
        }
        
        // 设置总数和当前页数据
        pb.setTotal((long) totalSize);
        pb.setItems(pageItems);
        PageBeanWithTotalPage<Category> pageBeanWithTotalPage = new PageBeanWithTotalPage<>();
        BeanUtil.copyProperties(pb, pageBeanWithTotalPage);
        pageBeanWithTotalPage.setTotalPage(totalSize / CATEGORY_SIZE + (totalSize % CATEGORY_SIZE == 0 ? 0 : 1));

        return pageBeanWithTotalPage;
    }

    @Override
    public void addCategory(String categoryName) {
        categoryMapper.addCategory(categoryName);
    }
}